package com.sqsf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqsf.javabean.Role;
import com.sqsf.javabean.Video;
import com.sqsf.service.VideoService;
import com.sqsf.service.VideoStuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/videoStu")
public class VideoStuController {
    @Autowired
    VideoStuService videoStuService;
    @Autowired
    VideoService videoService;

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, @RequestParam(value = "page",required = false,defaultValue = "1") int page, @RequestParam(value = "limit",required = false,defaultValue = "5")int limit,@RequestParam(value = "courseName",required = false,defaultValue = "")String courseName){
        PageHelper.startPage(page, limit);
        List<Video> all = videoStuService.findAll(courseName);
        PageInfo<Video> pageInfo=new PageInfo<>(all);
        request.setAttribute("pageInfo",pageInfo);
        request.setAttribute("value",courseName);
        return "/videoStu/video-list";
    }

    @RequestMapping("/download")
    public void download(@RequestParam("id") int id, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        Video video = videoService.findById(id);
        String fileName=video.getVideoUrl();
        String titleName=video.getTitle()+fileName.substring(fileName.lastIndexOf("."));
        System.out.println("--------------------------------"+titleName);
        File file = new File("d://upload",fileName);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentType("application/json");
            response.getWriter().write("{\"msg\":\"该文件不存在\"}");
            return;
        }
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(titleName,"utf-8"));
        response.setContentType("application/octet-stream");
        //1kb
        byte[] list = new byte[1024];
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        int len;
        while((len = inputStream.read(list)) != -1){
            outputStream.write(list,0,len);
        }
    }

}
